/**
 * api/applys
 */

const defaultToInteger = require('../../../utils/default-to-integer');
const sortQB = require('../../../utils/sort-qb')();
const md5 = require('../../../utils/md5');
const applyHandler = require('../../../services/apply-hander');
const applyConfirm = require('../../../services/apply-confirm');


module.exports = function(app) {
    const router = app.router;
    const Apply = app.models.Apply;
    const Ticket = app.models.Ticket;
    const User = app.models.User;

    /**
     * @apiVersion 1.0.0
     * @apiGroup Apply
     * @api {get} /applys 获取角色列表
     * @apiParam {Number} status=ONLINE 上架状态 `0:OFFLINE, 1:ONLINE, 2:DEBUG`
     * @apiParam {Number} locate=home 角色位置 `home, post, user, home_user: 首页横幅`
     * @apiParam {Number} type=image 角色类型 `image, video`
     * @apiParam {Number} since 指定时间，单位秒
     * @apiParam {Number} page_size=20 分页大小
     * @apiParam {Number} page_num=1 页码
     * @apiParam {String} sort=priority-desc 排序，支持 `id-desc, id-asc, priority-desc`
     *
     * @apiParam {Number} status=1 `0:OFFLINE, 1:ONLINE, 2:DEBUG` 上架状态
     * @apiParam {Number} title 标题
     * @apiParam {String} locate 角色位置
     * @apiParam {String} scope 角色范围
     * @apiParam {String} scope_info 角色范围配置
     * @apiParam {String} type 角色类型 ``
     * @apiParam {String} asset_url 资源 URL
     * @apiParam {Number} width 宽
     * @apiParam {Number} height 高
     * @apiParam {Number} duration 角色时长，单位毫秒
     * @apiParam {String} url 跳转URL `如果为空则不跳转，其余按 H5内 `openPage.url` 和 全局规则`
     * @apiParam {Number} priority 排序优先级
     * @apiParam {Number} start_time 开始时间，单位秒
     * @apiParam {Number} end_time 结束时间，单位秒
     *
     * @apiSuccess {Number} status 上架状态
     * @apiSuccess {String} locate 角色位置 `home: user: recommed: 推荐位`
     * @apiSuccess {String} scope 角色范围
     * @apiSuccess {String} scope_info 角色范围配置
     * @apiSuccess {String} type 角色类型
     * @apiSuccess {String} asset_url 资源 URL
     * @apiSuccess {Number} width 宽
     * @apiSuccess {Number} height 高
     * @apiSuccess {Number} duration 角色时长，单位毫秒
     * @apiSuccess {String} url 跳转 URL `如果为空则不跳转，其余按 H5内 `openPage.url` 和 全局规则`
     ** @apiSuccess {Number} params 请求参数
     * @apiSuccess {Number} priority 排序优先级
     * @apiSuccess {Number} start_time 开始时间，单位秒
     * @apiSuccess {Number} end_time 结束时间，单位秒
     *
     * @apiSampleRequest
     */
    router.get('/applys', function *() {
        const query = this.query;

        const userId = this.headers['x-user'];

        const user = yield User.where({
            id: userId
        })
        .fetch({
            withRelated: ['role']
        });

        const role = user.related('role');

        // @TODO: 支持 scpoe 查询
        const applys = yield Apply.query(qb => {
            qb.where('deleted', Apply.NOT_DELETED);
            if(query.status !== 'all') {
                qb.where('status', query.status);
            }
            if(role.get('name').indexOf('管理员') < 0) {
                qb.where('creator', userId);
            }

            qb.orderBy('id', 'DESC');
            // sort
            // sortQB(qb, query.sort);
        })
        .fetchItems({
            page_size: query.page_size,
            page_num: query.page_num
        }, {
            withRelated: ['creator', 'types', 'parent', 'customer', 'leader']
        });

        this.body = applys;
    });

    router.get('/applys/:id', function *() {
        this.body = yield Apply.where({
            id: this.params.id
        })
        .fetch({
            require: true
        });
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Apply
     * @api {post} /applys 新建角色
     *
     * @apiParam {Number} status 上架状态
     * @apiParam {String} locate 角色位置
     * @apiParam {String} scope 角色范围
     * @apiParam {String} scope_info 角色范围配置
     * @apiParam {String} type 角色类型
     * @apiParam {String} asset_url 资源 URL
     * @apiParam {Number} width 宽
     * @apiParam {Number} height 高
     * @apiParam {Number} duration 角色时长，单位毫秒
     * @apiParam {String} url 跳转 URL，如果为空则不跳转，其余按 H5内 `openPage.url` 规则
     * @apiParam {Number} priority 排序优先级
     * @apiParam {Number} start_time 开始时间，单位秒
     * @apiParam {Number} end_time 结束时间，单位秒
     */
    router.post('/applys', function *() {
        let body = this.request.body;

        body.creator = this.headers['x-user'];


        yield applyHandler(body);

        this.body = body;
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Apply
     * @api {put} /applys/:id 修改角色
     *
     * @apiParam {Number} status 上架状态
     * @apiParam {String} locate 角色位置
     * @apiParam {String} scope 角色范围
     * @apiParam {String} scope_info 角色范围配置
     * @apiParam {String} type 角色类型 ``
     * @apiParam {String} recommend_type `home_recommend: 首页顶部推荐, feature_recommend: 特性（标签）推荐, templet_recommend 模板库推荐`
     * @apiParam {String} asset_url 资源 URL
     * @apiParam {Number} width 宽
     * @apiParam {Number} height 高
     * @apiParam {Number} duration 角色时长，单位毫秒
     * @apiParam {String} url 跳转URL `如果为空则不跳转，其余按 H5内 `openPage.url` 和 全局规则`
     * @apiParam {Number} priority 排序优先级
     * @apiParam {Number} start_time 开始时间，单位秒
     * @apiParam {Number} end_time 结束时间，单位秒
     *
     * @apiSuccess {Number} status 上架状态
     * @apiSuccess {String} locate 角色位置 `home: user: recommed: 推荐位`
     * @apiSuccess {String} scope 角色范围
     * @apiSuccess {String} scope_info 角色范围配置
     * @apiSuccess {String} type 角色类型
     * @apiSuccess {String} asset_url 资源 URL
     * @apiSuccess {Number} width 宽
     * @apiSuccess {Number} height 高
     * @apiSuccess {Number} duration 角色时长，单位毫秒
     * @apiSuccess {String} url 跳转 URL `如果为空则不跳转，其余按 H5内 `openPage.url` 和 全局规则`
     * @apiSuccess {Number} priority 排序优先级
     * @apiSuccess {Number} start_time 开始时间，单位秒
     * @apiSuccess {Number} end_time 结束时间，单位秒
     */
    router.put('/applys/:id', function *() {
        const body = this.request.body;

        if(+this.params.id === 0) {
            if(body.start_ticket_no && body.start_ticket_no) {
                const ticket = yield Ticket.where({
                    ticket_no: body.start_ticket_no
                })
                .fetch();

                const endTicket = yield Ticket.where({
                    ticket_no: body.end_ticket_no
                })
                .fetch();

                if(ticket.get('id') > endTicket.get('id')) {
                    this.throw('起始编号小于结束编号');
                }

                const tickets = yield Ticket.query(qb => {
                    qb.where('type_id', body.type_id);
                    qb.where('parent_id', body.parent_id);
                    qb.where('status', '<', Ticket.READY);
                    qb.where('id', '>=', ticket.get('id'));
                    qb.where('id', '<=', endTicket.get('id'));
                })
                .fetchAll();

                for(let i = 0; i < tickets.length; i++) {
                    tickets.models[i].set('status', Ticket.OFFLINE);

                    yield tickets.models[i].save();
                }

                this.body = body;
                return;
            }
            if(body.apply_id && +body.apply_id > 0) {
                yield Ticket.where({
                    apply_id: body.apply_id,
                    status: Ticket.READY
                })
                .save({
                    status: body.status,
                    end_time: new Date(Date.now() + (30 * 24 * 60 * 60 * 1000))
                }, {
                    method: 'update'
                });

                this.body = body;
                return;
            }
        }
        body.leader_id = this.headers['x-user'];
        body.id = this.params.id;

        if(body.end_time && +body.end_time > 0) {
            body.end_time = new Date(body.end_time * 1000);
        }

        if(body.start_time && +body.start_time > 0) {
            body.start_time = new Date(body.start_time * 1000);
        }
        // yield applyConfirm(body);

        yield Apply.where({
            id: this.params.id
        }).save({
            status: 1,
            price: body.price,
            leader_id: body.leader_id,
            pay_type: body.pay_type,
            b_percent: body.b_percent,
            remark: body.remark,
            apply_no: body.apply_no,
            end_time: body.end_time,
            start_time: body.start_time
        }, {
            method: 'update'
        });
        this.body = body;
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Apply
     * @api {delete} /applys/:id 删除角色
     */
    router.delete('/applys/:id', function *() {
        let apply = yield Apply.where({
            id: this.params.id
        })
        .fetch({
            require: true
        });

        yield Ticket.where({
            apply_id: apply.get('id')
        })
        .save({
            status: Ticket.OFFLINE
        }, {
            method: 'update'
        });

        this.body = this.params;
    });
};
